<script lang="ts" setup>
import { computed, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  DatePicker,
  Input,
  InputNumber,
  Modal,
  Select,
  Table,
  message,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { $t } from '#/locales';

// 凭证基本信息
const voucherInfo = ref({
  date: dayjs('2025-01-31'),
  number: '001',
  type: '记',
});

// 凭证类型选项
const voucherTypeOptions = [
  { label: '记', value: '记' },
  { label: '收', value: '收' },
  { label: '付', value: '付' },
  { label: '转', value: '转' },
];

// 会计科目选项
const accountSubjectOptions = [
  { label: '库存现金', value: '1001' },
  { label: '银行存款', value: '1002' },
  { label: '其他货币资金', value: '1012' },
  { label: '应收账款', value: '1122' },
  { label: '预付账款', value: '1131' },
  { label: '原材料', value: '1403' },
  { label: '库存商品', value: '1405' },
  { label: '固定资产', value: '1601' },
  { label: '累计折旧', value: '1602' },
  { label: '短期借款', value: '2101' },
  { label: '应付账款', value: '2112' },
  { label: '应交税金', value: '2221' },
  { label: '实收资本', value: '3101' },
  { label: '未分配利润', value: '3105' },
  { label: '主营业务收入', value: '5101' },
  { label: '主营业务成本', value: '5102' },
  { label: '销售费用', value: '6101' },
  { label: '管理费用', value: '6201' },
  { label: '财务费用', value: '6301' },
];

// 分录数据接口
interface VoucherEntry {
  accountSubject: string;
  creditAmount: number | null;
  debitAmount: number | null;
  id: number;
  summary: string;
}

const entries = ref<VoucherEntry[]>([
  {
    accountSubject: '',
    creditAmount: null,
    debitAmount: null,
    id: 1,
    summary: '',
  },
  {
    accountSubject: '',
    creditAmount: null,
    debitAmount: null,
    id: 2,
    summary: '',
  },
]);

// 计算合计
const totalDebit = computed(() => {
  return entries.value.reduce(
    (sum, entry) => sum + (entry.debitAmount || 0),
    0,
  );
});

const totalCredit = computed(() => {
  return entries.value.reduce(
    (sum, entry) => sum + (entry.creditAmount || 0),
    0,
  );
});

// 检查借贷平衡
const isBalanced = computed(() => {
  return Math.abs(totalDebit.value - totalCredit.value) < 0.01;
});

// 表格列配置
const columns = [
  {
    dataIndex: 'summary',
    key: 'summary',
    title: $t('accounting.entry.summary'),
    width: 200,
  },
  {
    dataIndex: 'accountSubject',
    key: 'accountSubject',
    title: $t('accounting.entry.accountSubject'),
    width: 200,
  },
  {
    children: [
      { dataIndex: 'yi', key: 'debit-yi', title: '亿', width: 40 },
      { dataIndex: 'qian', key: 'debit-qian', title: '千', width: 40 },
      { dataIndex: 'bai', key: 'debit-bai', title: '百', width: 40 },
      { dataIndex: 'shi', key: 'debit-shi', title: '十', width: 40 },
      { dataIndex: 'wan', key: 'debit-wan', title: '万', width: 40 },
      { dataIndex: 'qian2', key: 'debit-qian2', title: '千', width: 40 },
      { dataIndex: 'bai2', key: 'debit-bai2', title: '百', width: 40 },
      { dataIndex: 'shi2', key: 'debit-shi2', title: '十', width: 40 },
      { dataIndex: 'yuan', key: 'debit-yuan', title: '元', width: 40 },
      { dataIndex: 'jiao', key: 'debit-jiao', title: '角', width: 40 },
      { dataIndex: 'fen', key: 'debit-fen', title: '分', width: 40 },
    ],
    key: 'debitAmount',
    title: $t('accounting.entry.debitAmount'),
  },
  {
    children: [
      { dataIndex: 'yi', key: 'credit-yi', title: '亿', width: 40 },
      { dataIndex: 'qian', key: 'credit-qian', title: '千', width: 40 },
      { dataIndex: 'bai', key: 'credit-bai', title: '百', width: 40 },
      { dataIndex: 'shi', key: 'credit-shi', title: '十', width: 40 },
      { dataIndex: 'wan', key: 'credit-wan', title: '万', width: 40 },
      { dataIndex: 'qian2', key: 'credit-qian2', title: '千', width: 40 },
      { dataIndex: 'bai2', key: 'credit-bai2', title: '百', width: 40 },
      { dataIndex: 'shi2', key: 'credit-shi2', title: '十', width: 40 },
      { dataIndex: 'yuan', key: 'credit-yuan', title: '元', width: 40 },
      { dataIndex: 'jiao', key: 'credit-jiao', title: '角', width: 40 },
      { dataIndex: 'fen', key: 'credit-fen', title: '分', width: 40 },
    ],
    key: 'creditAmount',
    title: $t('accounting.entry.creditAmount'),
  },
  {
    key: 'action',
    title: '操作',
    width: 100,
  },
];

// 添加分录行
const addEntry = () => {
  const newId = Math.max(...entries.value.map((e) => e.id)) + 1;
  entries.value.push({
    accountSubject: '',
    creditAmount: null,
    debitAmount: null,
    id: newId,
    summary: '',
  });
};

// 删除分录行
const deleteEntry = (id: number) => {
  if (entries.value.length > 1) {
    entries.value = entries.value.filter((entry) => entry.id !== id);
  }
};

// 清空表单
const clearForm = () => {
  Modal.confirm({
    content: '确定要清空所有数据吗？',
    onOk() {
      voucherInfo.value = {
        date: dayjs('2025-01-31'),
        number: '001',
        type: '记',
      };
      entries.value = [
        {
          accountSubject: '',
          creditAmount: null,
          debitAmount: null,
          id: 1,
          summary: '',
        },
        {
          accountSubject: '',
          creditAmount: null,
          debitAmount: null,
          id: 2,
          summary: '',
        },
      ];
      message.success('已清空所有数据');
    },
    title: '确认清空',
  });
};

// 验证凭证数据
const validateVoucher = (): boolean => {
  // 检查是否有分录
  if (entries.value.length === 0) {
    message.error('请至少添加一条分录');
    return false;
  }

  // 检查分录是否完整
  for (const entry of entries.value) {
    if (!entry.summary.trim()) {
      message.error('请填写摘要');
      return false;
    }
    if (!entry.accountSubject) {
      message.error('请选择会计科目');
      return false;
    }
    if (!entry.debitAmount && !entry.creditAmount) {
      message.error('请填写借方或贷方金额');
      return false;
    }
  }

  // 检查借贷平衡
  if (!isBalanced.value) {
    message.error('借贷不平衡，请检查金额');
    return false;
  }

  return true;
};

// 保存凭证
const saveVoucher = () => {
  if (!validateVoucher()) {
    return;
  }

  const voucherData = {
    entries: entries.value,
    voucherInfo: voucherInfo.value,
  };

  // 这里可以调用API保存数据
  console.warn('保存凭证:', voucherData);
  message.success('凭证保存成功');
};

// 保存并新增
const saveAndNew = () => {
  if (!validateVoucher()) {
    return;
  }

  saveVoucher();
  setTimeout(() => {
    clearForm();
  }, 500);
};

// 显示快捷键
const showShortcuts = () => {
  Modal.info({
    content: `
      快捷键说明：
      Ctrl + S: 保存凭证
      Ctrl + N: 新增分录
      Ctrl + D: 删除当前分录
      Tab: 切换到下一个输入框
      Enter: 确认输入并移动到下一行
    `,
    title: '快捷键说明',
  });
};

// 金额格式化函数
const formatAmount = (amount: null | number): string => {
  if (!amount) return '0.00';
  return amount.toLocaleString('zh-CN', {
    maximumFractionDigits: 2,
    minimumFractionDigits: 2,
  });
};

// 将金额分解为各个位数
const parseAmountToDigits = (amount: number | null) => {
  if (!amount) return {};
  const amountStr = amount.toFixed(2);
  const [integerPart, decimalPart] = amountStr.split('.');
  const paddedInteger = integerPart.padStart(9, '0');

  return {
    bai: paddedInteger[6] === '0' ? '' : paddedInteger[6],
    bai2: paddedInteger[3] === '0' ? '' : paddedInteger[3],
    fen: decimalPart[1] === '0' ? '' : decimalPart[1],
    jiao: decimalPart[0] === '0' ? '' : decimalPart[0],
    qian: paddedInteger[7] === '0' ? '' : paddedInteger[7],
    qian2: paddedInteger[4] === '0' ? '' : paddedInteger[4],
    shi: paddedInteger[5] === '0' ? '' : paddedInteger[5],
    shi2: paddedInteger[2] === '0' ? '' : paddedInteger[2],
    wan: paddedInteger[1] === '0' ? '' : paddedInteger[1],
    yi: paddedInteger[0] === '0' ? '' : paddedInteger[0],
    yuan: paddedInteger[8] === '0' ? '' : paddedInteger[8],
  };
};
</script>

<template>
  <Page auto-content-height>
    <!-- 页面头部 -->
    <div class="mb-4 flex items-center justify-between">
      <!-- 左侧公司信息 -->
      <div class="flex items-center space-x-4">
        <span class="text-lg font-medium">北京神州源科技有限公司</span>
      </div>

      <!-- 右侧操作按钮 -->
      <div class="flex items-center space-x-2">
        <Button @click="clearForm">
          {{ $t('accounting.entry.clear') }}
        </Button>
        <Button type="primary" @click="saveVoucher">
          {{ $t('accounting.entry.save') }}
        </Button>
        <Button type="primary" @click="saveAndNew">
          {{ $t('accounting.entry.saveAndNew') }}
        </Button>
      </div>
    </div>

    <!-- 凭证信息卡片 -->
    <Card class="mb-4">
      <!-- 凭证头部信息 -->
      <div class="mb-4 flex items-center space-x-6">
        <div class="flex items-center space-x-2">
          <span>{{ $t('accounting.entry.voucherType') }}：</span>
          <Select
            v-model:value="voucherInfo.type"
            :options="voucherTypeOptions"
            style="width: 80px"
          />
        </div>

        <div class="flex items-center space-x-2">
          <span>{{ $t('accounting.entry.voucherNumber') }}：</span>
          <Input v-model:value="voucherInfo.number" style="width: 100px" />
        </div>

        <div class="flex items-center space-x-2">
          <span>{{ $t('accounting.entry.voucherDate') }}：</span>
          <DatePicker
            v-model:value="voucherInfo.date"
            format="YYYY-MM-DD"
          />
        </div>
      </div>

      <!-- 分录表格 -->
      <div class="mb-4">
        <Table
          :columns="columns"
          :data-source="entries"
          :pagination="false"
          bordered
          size="small"
        >
          <!-- 自定义单元格内容 -->
          <template #bodyCell="{ column, record }">
            <!-- 摘要列 -->
            <template v-if="column.key === 'summary'">
              <Input
                v-model:value="record.summary"
                placeholder="请输入摘要"
              />
            </template>

            <!-- 会计科目列 -->
            <template v-else-if="column.key === 'accountSubject'">
              <Select
                v-model:value="record.accountSubject"
                :options="accountSubjectOptions"
                placeholder="请选择科目"
                show-search
                style="width: 100%"
              />
            </template>

            <!-- 借方金额各位数 -->
            <template
              v-else-if="
                column.key?.startsWith('debit-') &&
                column.key !== 'debitAmount'
              "
            >
              <div class="text-center">
                {{
                  parseAmountToDigits(record.debitAmount)[
                    column.key.replace('debit-', '').replace('2', '')
                  ]
                }}
              </div>
            </template>

            <!-- 贷方金额各位数 -->
            <template
              v-else-if="
                column.key?.startsWith('credit-') &&
                column.key !== 'creditAmount'
              "
            >
              <div class="text-center">
                {{
                  parseAmountToDigits(record.creditAmount)[
                    column.key.replace('credit-', '').replace('2', '')
                  ]
                }}
              </div>
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <div class="flex space-x-1">
                <Button size="small" type="link" @click="addEntry">
                  <IconifyIcon icon="ant-design:plus-outlined" />
                </Button>
                <Button
                  v-if="entries.length > 1"
                  danger
                  size="small"
                  type="link"
                  @click="deleteEntry(record.id)"
                >
                  <IconifyIcon icon="ant-design:delete-outlined" />
                </Button>
              </div>
            </template>
          </template>
        </Table>

        <!-- 金额输入区域 -->
        <div class="mt-4 space-y-2">
          <div
            v-for="(entry, index) in entries"
            :key="entry.id"
            class="flex items-center space-x-4 rounded border p-2"
          >
            <span class="w-16 text-sm">第{{ index + 1 }}行:</span>
            <div class="flex items-center space-x-2">
              <span class="text-sm">借方:</span>
              <InputNumber
                v-model:value="entry.debitAmount"
                :precision="2"
                placeholder="0.00"
                style="width: 120px"
              />
            </div>
            <div class="flex items-center space-x-2">
              <span class="text-sm">贷方:</span>
              <InputNumber
                v-model:value="entry.creditAmount"
                :precision="2"
                placeholder="0.00"
                style="width: 120px"
              />
            </div>
          </div>
        </div>

        <!-- 合计行 -->
        <div class="mt-4 flex items-center justify-between border-t pt-2">
          <span class="font-medium">{{ $t('accounting.entry.total') }}：</span>
          <div class="flex space-x-4">
            <span
              :class="{ 'text-red-500': !isBalanced }"
              class="font-medium"
            >
              借方合计：{{ formatAmount(totalDebit) }}
            </span>
            <span
              :class="{ 'text-red-500': !isBalanced }"
              class="font-medium"
            >
              贷方合计：{{ formatAmount(totalCredit) }}
            </span>
            <span
              v-if="!isBalanced"
              class="text-red-500 text-sm"
            >
              (借贷不平衡)
            </span>
          </div>
        </div>
      </div>
    </Card>

    <!-- 页面底部 -->
    <div class="flex items-center justify-between">
      <div class="flex items-center space-x-4">
        <span>{{ $t('accounting.entry.creator') }}：大老板</span>
      </div>

      <Button @click="showShortcuts">
        {{ $t('accounting.entry.shortcuts') }}
      </Button>
    </div>
  </Page>
</template>

<style scoped>
.ant-table-thead > tr > th {
  font-weight: 600;
  text-align: center;
  background-color: #fafafa;
}

.ant-table-tbody > tr > td {
  padding: 4px 2px;
  text-align: center;
}

.ant-table-tbody > tr > td:first-child,
.ant-table-tbody > tr > td:nth-child(2) {
  text-align: left;
}

.ant-input-number {
  width: 100%;
}

.ant-select {
  width: 100%;
}
</style>